<?php

namespace app\withdrawal\controller;

use app\model\AdminAgent;
use app\model\Withdrawal as WithdrawalModel;
use app\common\controller\Adminbase;
use think\Db;

class Agent extends Adminbase
{
    public function index()
    {
        $model = 'Withdrawal';

        if ($this->request->isAjax()) {
            $map      = $this->buildParamsMap();
            $page     = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : 20;

            $list   = WithdrawalModel::where($map)
                ->where('type', 2)
                ->field('*')
                ->withAttr('withdrawal_money', function ($value) {
                    return $value ? number_format($value / 100, 2) : "0.00";
                })
                ->withAttr('charge_money', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : "0.00";
                })
                ->withAttr('money', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : "0.00";
                })
                ->append(['status_text', 'withdrawal_status_text'])
                ->with(['agent'])
                ->page($page, $pageSize)
                ->select();
            $total  = WithdrawalModel::where($map)->where('type', 2)->count();
            $result = ["code" => 0, "count" => $total, "data" => $list];
            return json($result);
        }
        $tabList = [
            ['key' => '', 'value' => '全部'],
            ['key' => 0, 'value' => '待审核'],
            ['key' => 1, 'value' => '通过'],
            ['key' => 2, 'value' => '驳回'],
        ];

        //生成列表数据
        $builder = new \app\common\controller\ListBuilder();
        $builder
            ->setTabNav($tabList)
            ->setTabName('status')
            ->setDataUrl()
            ->setAddBtn(false)
            ->setDelAllBtn(false)
            ->setDelBtn(false)
            ->setSwitchTpl('amplifyTpl', 'image')
            ->setModel($model)
            ->setLimit()
            ->addTableColumn('id', 'ID', 80, null, true)
            ->addTableColumn('user_id', '团长ID', 100)
            ->addTableColumn('agent_name', '团长名称', 120)
            ->addTableColumn('name', '收款人姓名', 120)
            ->addTableColumn('image', '收款码图片', 120, '#amplifyTpl')
            ->addTableColumn('money', '打款金额' . '(元)', 120)
            ->addTableColumn('withdrawal_money', '提现金额' . '(元)', 120)
            ->addTableColumn('charge_money', '提现手续费' . '(元)', 150)
            ->addTableColumn('status_text', '审核状态', 120)
            ->addTableColumn('withdrawal_status_text', '提现状态', 120)
            ->addTableColumn('create_time', '申请时间', 200)
            ->addTableOperation()
            ->setFieldSelfBtn([
                ['type' => 'form', 'title' => '审核', 'class' => 'layui-btn-normal', 'url' => url('audit'), 'field' => 'status', 'value' => '0'],
                ['type' => 'confirm', 'title' => '确认打款', 'class' => 'layui-btn-normal', 'url' => url('confirm'), 'msg' => '是否确认已打款？', 'field' => 'withdrawal_status', 'value' => '1'],
            ])
            ->returnForm();

        $this->assign('module', 'user');
        return $this->fetch('admin@common/lists');
    }

    public function audit()
    {
        $id    = $this->request->param('id/d');
        $info  = WithdrawalModel::find($id);
        $model = 'Withdrawal';

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if ($data['status'] == 2 && empty($data['remark'])) {
                return json(['code' => -1, 'msg' => '请填写拒绝原因']);
            }
            $save = [
                'status' => $data['status'],
                'remark' => $data['remark'],
            ];
            if ($data['status'] == 1) {
                $save['withdrawal_status'] = 1;
            }
            Db::startTrans();
            //驳回需要退回用户提现余额
            $user_res = true;
            if ($data['status'] == 2) {
                $save['withdrawal_status'] = 3;
                $info                      = $info->getData();
                $user                      = AdminAgent::field('id, money')->where('id', $info['user_id'])->find();
                $user_res                  = AdminAgent::update([
                    'id'    => $info['user_id'],
                    'money' => $user['money'] + $info['withdrawal_money'],
                ]);
            }
            $res = WithdrawalModel::where('id', $data['id'])->update($save);
            if ($res && $user_res) {
                Db::commit();
            }
            return json(['code' => 0, 'msg' => '操作成功']);
        }

        if (isset($id) && $id > 0) {
            $this->assign('id', $id);
            $this->assign('action', 2);
        }

        $text    = [0 => '待审核', 1 => '通过', 2 => '驳回'];
        $builder = new \app\common\controller\FormBuilder();
        $builder
            ->setUrl('audit')
            ->setModel($model)
            ->setSuccessUrl()
            ->addFormItem('status', 'radio', '审核状态', '', $text)
            ->addFormItem('remark', 'textarea', '审核内容')
            ->setFormData($info)
            ->returnForm();
        $this->assign('is_verify', 0);
        return $this->fetch('admin@common/form');
    }

    public function confirm()
    {
        $id   = $this->request->param('id/d');
        $info = WithdrawalModel::find($id)->getData();
        if ($info['status'] != 1) {
            return json(['code' => -1, 'msg' => '提现记录未审核通过']);
        }
        if ($info['withdrawal_status'] == 2) {
            return json(['code' => -1, 'msg' => '提现记录已处理成功，请勿重复操作']);
        }
        $res = WithdrawalModel::where('id', $id)->update([
            'withdrawal_status' => 2,
        ]);
        if ($res) {
            return json(['code' => 0, 'msg' => '操作成功']);
        }
        return json(['code' => -1, 'msg' => '操作失败']);
    }

}
